package br.com.jdobjs.core.mock;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.Resource;
import org.drools.io.ResourceFactory;

import br.com.jdobjs.core.DefaultRuleSecurityConfig;
import br.com.jdobjs.core.RuleSecurityConfig;
import br.com.jdobjs.core.RuleSecurityConfigurationException;
import br.com.jdobjs.core.UserCredentialsResolver;

public class RuleSecurityConfigMock implements RuleSecurityConfig {

	private ApplicationPrincipal principal;
	private String drlFilePath;

	public RuleSecurityConfigMock(ApplicationPrincipal principal,
			String drlFilePath) {
		super();
		this.principal = principal;
		this.drlFilePath = drlFilePath;
	}

	@Override
	public KnowledgeBase getKnowledgeBase() {
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();

		Resource resource = ResourceFactory.newClassPathResource(drlFilePath,
				DefaultRuleSecurityConfig.class);
		KnowledgeBase knowledgeBase;
		if (resource == null) {
			knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
		} else {
			kbuilder.add(resource, ResourceType.DRL);
			if (kbuilder.hasErrors()) {
				throw new RuleSecurityConfigurationException(kbuilder
						.getErrors());
			}

			knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
			knowledgeBase.addKnowledgePackages(kbuilder.getKnowledgePackages());
		}
		return knowledgeBase;
	}

	@Override
	public UserCredentialsResolver getUserCredentialsResolver() {
		return new UserCredentialsResolver() {

			@Override
			public Object getUserCredentials() {
				return principal;
			}
		};
	}
}
